// relay_server.go - 中继服务器代码
package main

import (
	"fmt"
	"net"
	"sync"
)

type ClientInfo struct {
	addr  *net.UDPAddr
}

func main() {
	serverAddr, err := net.ResolveUDPAddr("udp", "0.0.0.0:8888")
	if err != nil {
		panic(err)
	}

	conn, err := net.ListenUDP("udp", serverAddr)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	clients := make(map[string]*ClientInfo)
	clientCounter := 0
	buffer := make([]byte, 1024)

	fmt.Println("Relay server started on port 8888")

	for {
		n, addr, err := conn.ReadFromUDP(buffer)
		if err != nil {
			fmt.Println("Read error:", err)
			continue
		}

		msg := string(buffer[:n])
		fmt.Printf("Received %d bytes from %s: %s\n", n, addr, msg)

		switch msg {
		case "REGISTER":
			// 客户端注册
			clientID := fmt.Sprintf("client%d", clientCounter)

			// TODO：重复注册
			clients[clientID] = &ClientInfo{addr: addr}
			fmt.Printf("Registered %s (%s)\n", clientID, addr)
			clientCounter++

			// 简单处理：当有两个客户端时交换信息
			// TODO： 这里应该转发消息到所有的其他客户端

			if clientCounter == 2 {
				// 获取客户端地址
				clientList := make([]*net.UDPAddr, 0, 2)
				for _, info := range clients {
					clientList = append(clientList, info.addr)
				}

				// 发送对端地址
				conn.WriteToUDP([]byte(clientList[1].String()), clientList[0])
				conn.WriteToUDP([]byte(clientList[0].String()), clientList[1])

				// 重置计数器以便后续测试
				clientCounter = 0
				clients = make(map[string]*ClientInfo)
			}
		}
	}
}